<?php
class MySqlBackService
{
	private $adminDao;
	
	public function __construct(){
		$this->adminDao			= new AdminDao();
	}
	
	public function backupTables($prefix,$saveFile)
	{
		set_time_limit(0);
		$saveFile	= C('LtConfig')->get('db.backup.path').$saveFile;
		$fh			= fopen($saveFile,'w');
		if(!$fh)
		{
			$this->showJsMessage ('打开备份文件出错');
			return false;
		}
		$tables	= $this->getTables($prefix);
		if($tables)
		{
			foreach($tables as $table)
			{
				//缓存表不备份
				if(strpos($table,'product_cache')>0)
				{
					continue;
				}
				$this->showJsMessage ('正在备份表 '.$table.'...');
				$sql	= $this->data2sql($table);
				fwrite($fh,$sql);
			}
		}
		fclose($fh);
		$this->showJsMessage ('备份完毕，文件路径：'.$saveFile.',请下载后及时删除备份文件，防止被恶意下载');
	}
	
	public function restore($restoreFile)
	{
		set_time_limit(0);
		$restoreFile	= C('LtConfig')->get('db.backup.path').$restoreFile;
		if(!is_file($restoreFile))
		{
			$this->showJsMessage ($restoreFile.'不存在，请先上传restore.sql');
		}
		else
		{
			$sql	= file_get_contents($restoreFile);
			$this->runSql($sql);
			unlink($restoreFile);
			$this->showJsMessage ('还原完毕');
		}
	}
	
	public function runSql($sql) {
		$sql 		= str_replace("\r", "\n", $sql);
		$ret 		= array();
		$num 		= 0;
		foreach(explode(";\n", trim($sql)) as $query)
		{
			$queries 	= preg_split("/\n+/", trim($query));
			$ret[$num]	= '';
			foreach($queries as $query)
			{
				$tmp		= trim($query);
				$ret[$num] 	.= $tmp[0] == '#' || $tmp[0].$tmp[1] == '--' ? '' : $query;
			}
			$num++;
		}
		foreach($ret as $query)
		{
			$query 	= trim($query);
			
			if($query)
			{
				
				if(substr($query, 0, 12) == 'CREATE TABLE')
				{
					$name 	= preg_replace("/CREATE TABLE\s+`?([a-z0-9_]+)`? .*/is", "\\1", $query);
					
					$this->adminDao->getDbh()->query($query);
					
					if(mysql_errno())
					{
						$this->showJsMessage('还原表 '.$name.' 出错:'.mysql_error());
					}
					else
					{
						$this->showJsMessage('还原表 '.$name.' 成功');
					}
				}
				else
				{
					$this->adminDao->getDbh()->query($query);
				}
			}
		}
	}
	
	private function showJsMessage($message) {
		echo '<script type="text/javascript">showMessage(\''.addslashes($message).' \');</script>'."\r\n";
		flush();
		ob_flush();
	}
	
	public function getTables($prefix)
	{
		$tmp 	= $this->adminDao->getDbh()->query("SHOW TABLES LIKE '".str_replace('_','\_',$prefix)."%'");
		$tables	= array();
		if($tmp)
		{
			foreach($tmp as $tv)
			{
				foreach($tv as $tvv)
				{
					$tables[]	= $tvv;
				}
			}
		}
		return $tables;
	}
	
	public function data2sql($table)
	{
		$tableDump 		= "DROP TABLE IF EXISTS $table;\n";
		$createTable 	= $this->adminDao->getDbh()->query("SHOW CREATE TABLE $table");
		$tableDump 		.= $createTable[0]['Create Table'].";\n\n";
		
		$rows 			= $this->adminDao->getDbh()->query("SELECT * FROM $table");
		if($rows)
		{
			foreach($rows as $row)
			{
				$comma = "";
				$tableDump 	.= "INSERT INTO $table VALUES(";
				foreach($row as $rk=>$rv)
				{
					if(is_null($rv))
					{
						$tableDump 	.= $comma.'NULL';
					}
					else
					{
						$tableDump 	.= $comma."'".mysql_escape_string($rv)."'";
					}
					$comma = ",";
				}
				$tableDump .= ");\n";
			}
		}
		
		$tableDump .= "\n";
		return $tableDump;
	}
}
?>